package com.gopay.common.log.collect;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志采集者
 * 
 * @LogCollector.java
 * @author dak.wang
 * @2016年4月20日 上午10:09:39 www.gopay.com.cn Inc.All rights reserved.
 */
public class LogCollector {

    private static ThreadLocal<LogStack<LogBag>> tlStack = new ThreadLocal<LogStack<LogBag>>();

    public static void produce(LogBag logBag) {
        LogStack<LogBag> stack = tlStack.get();
        if (stack == null) {
            stack = new LogStack<LogBag>();
        }

        stack.push(logBag);

        tlStack.set(stack);

    }

    public static LogBag consume() {
        LogStack<LogBag> stack = tlStack.get();

        return stack.pop();
    }

    public static LogBag peek() {
        LogStack<LogBag> stack = tlStack.get();

        return stack.peek();
    }

    public static int getElementIndex(String bagId) {
        int idx = -1;

        LogStack<LogBag> stack = tlStack.get();
        if (!stack.isEmpty()) {
            List<LogBag> list = stack.getList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(bagId)) {
                    return i;
                }
            }
        }

        return idx;
    }

    public static boolean isParentHasTransactional(int elementIndex) {
        LogStack<LogBag> stack = tlStack.get();
        if (!stack.isEmpty()) {
            List<LogBag> list = stack.getList();
            for (int i = 0; i < list.size() && i < elementIndex; i++) {
                if (list.get(i).isHasTransactionalAnno()) {
                    return true;
                }
            }
        }

        return false;
    }

    public static List<LogBag> popSelfAndChildrenByElementIndex(int elementIndex) {
        List<LogBag> rsList = new ArrayList<LogBag>();

        LogStack<LogBag> stack = tlStack.get();
        if (!stack.isEmpty()) {
            List<LogBag> list = stack.getList();
            if (elementIndex < list.size() && elementIndex > -1) {
                int n = list.size() - elementIndex;
                for (int i = 0; i < n; i++) {
                    rsList.add(stack.pop());
                }
            }

        }

        return rsList;
    }

}
